package pun.potato;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;

public class LoginFragment extends Fragment {

	//THESE ARE VARIABLES FOR FACEBOOK
	private static final String TAG = "LoginFragment";
	private UiLifecycleHelper uiHelper;
	ProgressDialog pDialog;
	String facebookName;
	String facebookid;
	String partnerFacebookId = "";
	boolean login = false;
	
	//THESE ARE VARIABLES FOR LOGGING IN NORMALLY
	Button loginButton;
	TextView register;
	EditText usernameField;
	EditText passwordField;
	EditText confirmPasswordField;
	String username;
	String password;
	String confirmPassword;
	int userid;
	int mojo;
	EditText u;
	EditText p;

	private Session.StatusCallback callback = new Session.StatusCallback() {

		@Override
		public void call(Session session, SessionState state, Exception exception) {
			onSessionStateChange(session, state, exception);

		}
	};

	private void onSessionStateChange(Session session, SessionState state, Exception exception){
		if(state.isOpened()){
			//Log.i(TAG, "Logged in...");
			if(session.isOpened()){
				Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

					@Override
					public void onCompleted(GraphUser user, Response response) {
						if(user != null && !login){
							//execute login here
							facebookName = user.getName();
							facebookid = user.getId();
							login = true;
							new FacebookLogin().execute("start");
							//Log.d(TAG, user.getName());
						}

					}
				});

			}
		}
		else{
			//Log.i(TAG, "Logged out...");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		Bundle e = getActivity().getIntent().getExtras();
		if(e != null){
			partnerFacebookId = e.getString("facebookId");
		}
		
		View view = inflater.inflate(R.layout.loginscreen, container, false);
		//TextView username = (TextView)view.findViewById(R.id.playerpoints);
		//TextView password = (TextView)view.findViewById(R.id.enemypoints);
		u = (EditText)view.findViewById(R.id.username_textbox);
		p = (EditText)view.findViewById(R.id.password_textbox);
		LoginButton authButton = (LoginButton)view.findViewById(R.id.authButton);
		authButton.setFragment(this);
		loginButton = (Button)view.findViewById(R.id.PlayButton);
		loginButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				new LoginPlayer().execute("start");
			}
			
		});
		
		register = (TextView)view.findViewById(R.id.textView4);
		
		
		register.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				Dialog registerDialog = createRegisterDialog();
				registerDialog.show();
				
			}
			
		});
		
		return view;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		uiHelper = new UiLifecycleHelper(getActivity(), callback);
		uiHelper.onCreate(savedInstanceState);

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onResume() {
		super.onResume();
		//for scenarios where the main activity is launched and the user session
		//is not null, the session state change notification may not be triggered
		//trigger it if it's open/closed
		Session session = Session.getActiveSession();
		if(session != null && (session.isOpened() || session.isClosed())){
			onSessionStateChange(session, session.getState(), null);
		}
		uiHelper.onResume();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
	}

	class FacebookLogin extends AsyncTask<String, String, String>{

		private boolean loginSuccess = false;
		private int userid;
		private String username;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = ProgressDialog.show(getActivity(), "", "Logging in with Facebook...", true);
		}

		@Override
		protected String doInBackground(String... params) {

			String name = facebookName.replace(" ", "%20");
			HttpClient client = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(Preferences.GetURL() + "facebookLogin.php?name=" + name + "&facebookid=" + facebookid + Preferences.GetLiveServerPreferences());

			try{
				HttpResponse response = client.execute(httpPost);
				String jsonString = EntityUtils.toString(response.getEntity());
				//Log.d(TAG, jsonString);
            	if(jsonString.equals("0")){
     	            loginSuccess = false;
     	        }
            	else{
            		JSONObject jObject = new JSONObject(jsonString);
            		if(jObject.getString("name") == "null" || jObject.getInt("id") < 0){
            			loginSuccess = false;
            		}
            		else{
            			loginSuccess = true;
	     	            username = jObject.getString("name");
	     	            userid = jObject.getInt("id");
	     	            mojo = jObject.getInt("mojo");
            		}
            	}
				
			}catch(ClientProtocolException e){
				//Log.d(TAG, "ClientProtocolException");
			}catch(IOException e){
				//Log.d(TAG, "IOException");
			}catch(JSONException e){
				//Log.d(TAG, "JSONException");
			}


			return null;

		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			pDialog.dismiss();
			if(loginSuccess){
				Intent intent = new Intent(getActivity(), MainMenu.class);
				intent.putExtra("userid", userid);
				intent.putExtra("username", username);
				intent.putExtra("facebookUser", true);
				intent.putExtra("partnerFacebookId", partnerFacebookId);
				intent.putExtra("mojo", mojo);
				//Log.d("goToMainMenu", "userid: " + userid + "username: " + username);
				startActivity(intent);
				getActivity().finish();
			}
		}


	}
	
	

	private void goToMainMenu(){
		
		Intent intent = new Intent(getActivity(), MainMenu.class);
		intent.putExtra("userid", userid);
		intent.putExtra("username", username);
		intent.putExtra("facebookUser", false);
		intent.putExtra("partnerFacebookId", partnerFacebookId);
		intent.putExtra("mojo", mojo);
		//Log.d("goToMainMenu", "userid: " + userid + "username: " + username);
		startActivity(intent);
		getActivity().finish();
	}
	
	class LoginPlayer extends AsyncTask<String, String, String>{

		ProgressDialog pDialog;
		boolean loginSuccess = false;

		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = ProgressDialog.show(getActivity(), "", "Logging in...", true);
		}
		
		@Override
		protected String doInBackground(String... arg0) {
			
			username = u.getText().toString();
			password = p.getText().toString(); 
			String nameToSend = username.replace(" ", "%20");
						
			loginSuccess = false;
			HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost(Preferences.GetURL() + "login.php?name=" + nameToSend + "&password=" + password + Preferences.GetLiveServerPreferences());
			 
	        try{
	        	HttpResponse response = httpclient.execute(httppost);
	            String jsonString = EntityUtils.toString(response.getEntity());
	            //Log.d("JsonString", jsonString);
	            try {
	            	if(jsonString.equals("0")){
	     	            loginSuccess = false;
	     	            }
	            	else {
	     	            //Log.d("Status", "logging in");
	     	            loginSuccess = true;
	     	            
	     	            JSONObject o = new JSONObject(jsonString);
	     	            username = o.getString("name");
	     	            userid = o.getInt("id");
	     	            mojo = o.getInt("mojo");
					}
				} catch (JSONException e) {
					loginSuccess = false;
					//Log.d("Error", "JSONException");
					e.printStackTrace();
				}
	        }catch(ClientProtocolException e){
	        	loginSuccess = false;
	        	//Log.e("Register", "ClientProtocolException");
	        }
	        catch(IOException e){
	        	loginSuccess = false;
	        	//Log.e("Register", "IOException");
	        }
			
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			pDialog.dismiss();
			
			if(loginSuccess){
				goToMainMenu();
			}
			else{
				Toast.makeText(getActivity(), "Please try again. Either your username or password was incorrect.", Toast.LENGTH_LONG).show();
			}
		}
	}
	
	private Dialog createRegisterDialog(){
		
		final View registerDialog = View.inflate(getActivity(), R.layout.registerdialog, null);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle("Register");
		builder.setIcon(0);
		
		builder.setPositiveButton("Register", new Dialog.OnClickListener() {

			@Override
			public void onClick(android.content.DialogInterface dialog,
					int which) {
				//execute register script here
				usernameField = (EditText)registerDialog.findViewById(R.id.editText1);
				passwordField = (EditText)registerDialog.findViewById(R.id.editText2);
				confirmPasswordField = (EditText)registerDialog.findViewById(R.id.editText3);
				username = usernameField.getText().toString();
				password = passwordField.getText().toString();
				confirmPassword = confirmPasswordField.getText().toString();
				//check any additional registration retrictions here
				if(!username.equals("") && !password.equals("")){
					if(password.equals(confirmPassword)){
						if(!password.contains("#") && !password.contains("%")&& !password.contains("&") && !password.contains("+") && !password.contains("\"") && !password.contains("`") && !password.contains("|") && !password.contains("{") && !password.contains("}") && !password.contains("\t") && !password.contains("^") && !password.contains("\\") && !password.contains("<") && !password.contains(">") && !password.contains("\n")){
							if(!username.contains("#") && !username.contains("%")&& !username.contains("&") && !username.contains("+") && !username.contains("\"") && !username.contains("`") && !username.contains("|") && !username.contains("{") && !username.contains("}") && !username.contains("\t") && !username.contains("^") && !username.contains("\\") && !username.contains("<") && !username.contains(">") && !username.contains("\n")){
								if(username.length() < 28){
									new RegisterPlayer().execute("start");
								}
								else{
									Toast.makeText(getActivity(), "Please try again. Your username was too long.", Toast.LENGTH_LONG).show();
								}
							}
							else{
								Toast.makeText(getActivity(), "Please try again. Your username contains an invalid character.", Toast.LENGTH_LONG).show();
							}	
						}
						else{
							Toast.makeText(getActivity(), "Please try again. Your password contains an invalid character", Toast.LENGTH_LONG).show();
						}
					}
					else{
						Toast.makeText(getActivity(), "Please try again. The passwords do not match.", Toast.LENGTH_LONG).show();
					}
				}
				else{
					Toast.makeText(getActivity(), "Please try again. Either your username or password is blank", Toast.LENGTH_LONG).show();
				}

				
			}
		});
		
		builder.setNegativeButton("Cancel", new Dialog.OnClickListener() {

			@Override
			public void onClick(android.content.DialogInterface arg0, int arg1) {
				//cancel
				
			}
		});
		
		
		builder.setView(registerDialog);
		
		
		return builder.create();
	}
	
	class RegisterPlayer extends AsyncTask<String, String, String>{

		ProgressDialog pDialog;
		boolean registerSuccess = false;
		boolean duplicateName = false;

		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = ProgressDialog.show(getActivity(), "", "Registering...", true);
		}
		
		@Override
		protected String doInBackground(String... arg0) {
						
			
			String nameToSend = username.replace(" ", "%20");
			registerSuccess = false;
			HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost(Preferences.GetURL() + "register.php?name=" + nameToSend + "&password=" + password + Preferences.GetLiveServerPreferences());
			
	        try{
	        	HttpResponse response = httpclient.execute(httppost);
	            String jsonString = EntityUtils.toString(response.getEntity());
	            if(jsonString.charAt(0) == 'D'){
		            if(jsonString.substring(0, 9).equals("Duplicate")){
		            	registerSuccess = false;
		            	duplicateName = true;
		            }
		            else{
		            	registerSuccess = false;
		            }
	            }
	            else{
		            userid = Integer.valueOf(jsonString);
		            registerSuccess = true;
	            }

	            
	            //Log.d("Register", jsonString);
	        }catch(ClientProtocolException e){
	        	registerSuccess = false;
	        	//Log.e("Register", "ClientProtocolException");
	        }
	        catch(IOException e){
	        	registerSuccess = false;
	        	//Log.e("Register", "IOException");
	        }
			
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			pDialog.dismiss();
			if(registerSuccess){
				goToMainMenu();
			}
			else{
				if(duplicateName){
					Toast.makeText(getActivity(), "We're sorry, the username you have chosen is already in use.", Toast.LENGTH_LONG).show();
				}
			}
		}	
		
	}





}
